import csv
import os
import time
import random
from DrissionPage import ChromiumPage
import re
import json

class DpTaobao:
    def __init__(self,home_page, pro_name, page_name):
        self.page = ChromiumPage()
        self.home_page = home_page
        self.pro_name = pro_name
        self.page_name = page_name

    def get_home_page(self):
        self.page.get(self.home_page)

    def search_product(self):
        self.page.ele('xpath://*[@id="q"]').input(self.pro_name)
        time.sleep(random.uniform(3, 6))
        self.page.ele('xpath://button[@class="btn-search tb-bg"]').click()

    def choice_price_segment(self, num):
        price_segment_path = f'xpath://div[@class="PercentPicker--itemWrap--IkqNzOh"][{num}]'
        self.page.ele(price_segment_path).click()

    def select_salse_sort(self):
        time.sleep(random.uniform(1, 4))
        self.page.ele('xpath://div[@class="next-tabs-nav-scroll"]//li[@class="next-tabs-tab SortBar--customTabItem--YnxmQgr"][1]').click()

    # 定义一个函数来向下滚动页面
    def scroll_down(self):
        self.page.run_js('window.scrollBy(0, 2*window.innerHeight);')  # 向下滚动两个视窗高度
        time.sleep(random.randint(1, 3))  # 等待间隔时间，单位是秒

    def flip_page(self):
        time.sleep(random.uniform(4, 9))
        self.page.ele('xpath://button[@class="next-btn next-medium next-btn-normal next-pagination-item next-next"]').click()

    def pars_page(self, mtopjsonp):
        res_json = re.findall('mtopjsonp\d+\((.*)\)', mtopjsonp)[0]
        mtop_data = json.loads(res_json)
        itemsArray = mtop_data['data']['itemsArray']
        return itemsArray

    def write_csv(self, itemsArray):
        csv_columns = ['商品名', '价格', '销量', '发货地', '店铺名', '宝贝链接']
        filename = f"{self.pro_name}.csv"
        if not os.path.isfile(filename):
            with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
                writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
                writer.writeheader()

        with open(filename, 'a', newline='', encoding='utf-8') as csvfile:
            writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
            for item in itemsArray:
                writer.writerow({
                    '商品名': item['title'],
                    '价格': item['priceWap'],
                    '销量': item['realSales'],
                    '发货地': item['procity'],
                    '店铺名': item['shopInfo']['title'],
                    '宝贝链接': item['auctionURL']
                })

    def main(self):
        self.get_home_page()
        # input('请登录后按回车键继续')
        self.page.listen.start('h5/mtop.relationrecommend.wirelessrecommend.recommend/2.0')
        self.search_product()
        self.select_salse_sort()
        for ll in range(1,3):
            self.scroll_down()
        mtopjsonp = self.page.listen.wait().response.body
        itemsArray = self.pars_page(mtopjsonp)
        self.write_csv(itemsArray)
        for i in range(1, self.page_name):
            self.flip_page()
            time.sleep(random.uniform(1, 2))
            for tt in range(1,5):
                self.scroll_down()
                time.sleep(random.uniform(3, 7))
            mtopjsonp = self.page.listen.wait().response.body
            itemsArray = self.pars_page(mtopjsonp)
            self.write_csv(itemsArray)

        input('确认完成后按回车键继续')
        self.page.close()

# if __name__ == '__main__':
#     pro_name = input('请输入商品名：')
#     dp_taobao = DpTaobao('https://www.taobao.com', pro_name, 2)
#     dp_taobao.main()